package com.sakura.demo.auth.config;

import com.sakura.demo.auth.jwt.JwtTokenEnhancer;
import com.sakura.demo.auth.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zhengcan
 * @Date: 2022/5/12
 * @Description: 授权认证服务器：token存入内存模式
 * @Version: 1.0.0 创建
 */
//@Configuration
//@EnableAuthorizationServer
public class SakuraRedisAuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManagerBean;
    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Autowired
    private JwtTokenEnhancer jwtTokenEnhancer;
    @Autowired
    private JwtAccessTokenConverter accessTokenConverter;
    @Autowired
    private TokenStore sakuraTokenStore;

    /**
     * 配置授权的客户端信息
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 这里使用内存的模式配置，实际生产环境需使用jdbc模式
        // 也可以将客户端配置放在配置文件中处理，配置文件也可以从配置中心拉取实现动态修改
        clients.inMemory()
                // 给客户端签发的ID
                .withClient("sakura-app")
                // 给客户端签发的密钥
                .secret(passwordEncoder.encode("123456"))
                // 申请的权限范围
                .scopes("all")
                // 授权类型，允许多个授权类型并存
                .authorizedGrantTypes("password", "refresh_token", "authorization_code")
                // 授权码类型时授权后跳转页面
                .redirectUris("http://localhost:8848/nacos")
                // token有效期
                .accessTokenValiditySeconds(3600 * 24)
                // 刷新token有效期
                .refreshTokenValiditySeconds(3600 * 24 * 7);
    }

    /**
     * 使用密码模式授权时必须配置
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 整合JWT token
        List<TokenEnhancer> delegates = new ArrayList<>();
        // 配置一个自定义的jwt token增强器
        delegates.add(jwtTokenEnhancer);
        // 配置token转换器
        delegates.add(accessTokenConverter);
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        enhancerChain.setTokenEnhancers(delegates);

        endpoints
                // 配置密码验证管理器
                .authenticationManager(authenticationManagerBean)
                .userDetailsService(userDetailsService)
                // 配置token存储方式为redis
                .tokenStore(sakuraTokenStore)
                // 加入jwt token增强器
                .accessTokenConverter(accessTokenConverter)
                // token转换器
                .tokenEnhancer(enhancerChain);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 配置Endpoint,允许请求，不被Spring-security拦截
        security
                // 允许表单认证, 允许密码授权模式时进行用户的登录验证，需要表单提交的方式
                .allowFormAuthenticationForClients()
                // 开启/oauth/token_key 权限为：无需验证端口访问权限，无服务远程调用该接口时可不开启
                .tokenKeyAccess("permitAll()")
                // 开启/oauth/check_token 权限为：需要验证端口访问权限，无服务远程调用该接口时可不开启
                .checkTokenAccess("isAuthenticated()")
                // 配置BCrypt加密
                .passwordEncoder(passwordEncoder);
    }

}
